package com.techfort.affs;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.techfort.affs.mongoclient.MongolabClient;

public class AffsList extends Activity {


	private final String TAG = "info";
	private List<String> affs;
	private StoredAccountAdapter db;
	LinearLayout toprow;
	MongolabClient client;
	AlertDialog dialog;
	StringAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		db = new StoredAccountAdapter(getApplicationContext());
		db.open();

    	client = new MongolabClient("affs","users","4ead9de7e4b0e737eda86573");
		
		JSONObject joe = getCurrentUser();
		
        ListView affslist = (ListView) findViewById(R.id.affslist);
        toprow = (LinearLayout) findViewById(R.id.toprow);
        toprow.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				final Dialog dialog = new Dialog(AffsList.this);
				dialog.setContentView(R.layout.insert);
				dialog.setTitle("Insert Affirmation");
				dialog.show();
				
				Button create = (Button) dialog.findViewById(R.id.create);
				create.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						EditText newaff = (EditText) dialog.findViewById(R.id.newaff);
						affs.add(newaff.getText().toString());
						adapter.notifyDataSetChanged();
						dialog.dismiss();
						
						
						List<NameValuePair> qparams = new ArrayList<NameValuePair>();
						qparams.add(new BasicNameValuePair("q","{\"username\":\"" + db.getAccount() + "\"}"));
						
						JSONObject user = client.findOne(qparams);
						JSONObject update = new JSONObject();
						JSONObject value = new JSONObject();
						try {
							value.put("affs", newaff.getText().toString());
							update.put("$push", value);
							client.update(user.getJSONObject("_id").getString("$oid"), update);
						} catch (JSONException e) {
							
							e.printStackTrace();
						}
						
					}
				});
			}
		});
        
        try {
			JSONArray array = joe.getJSONArray("affs");
			affs = convertJSONArrayToList(array );

		} catch (JSONException e) {
			affs = new ArrayList<String>();
		} 
		adapter = new StringAdapter(AffsList.this, R.layout.affrow, affs); 
		affslist.setAdapter(adapter);
		
		
	}
	
	public List<String> convertJSONArrayToList(JSONArray array) throws JSONException{
    	
    	List<String> stringarray = new ArrayList<String>();
    	for(int i = 0; i < array.length(); i++){
    		stringarray.add(array.getString(i));
    	}
    	return stringarray;
    	
    }
    
    private class StringAdapter extends ArrayAdapter<String>{

    	private List<String> affs;
    	
		public StringAdapter(Context context, int textViewResourceId,
				List<String> objects) {
			super(context, textViewResourceId, objects);
			affs = objects;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;
			View v = convertView;
			if(v==null){
				
				LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.affrow, null);
			}
			LinearLayout ll = (LinearLayout) v.findViewById(R.id.row);
			
			TextView id = (TextView) v.findViewById(R.id.affnum);
			id.setText(Integer.toString(position + 1));
			TextView tv = (TextView) v.findViewById(R.id.afftext);
			tv.setText(affs.get(position));
			
			ll.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					Log.i(TAG,"item clicked " + pos);
					AlertDialog.Builder builder = new AlertDialog.Builder(AffsList.this);
					builder.setMessage("Delete the affirmation: \"" + affs.get(pos) +  "\"?");
					builder.setPositiveButton("delete", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							String aff = affs.get(pos);
							affs.remove(pos);
							notifyDataSetChanged();
							
							
							JSONObject update = new JSONObject();
							JSONObject value = new JSONObject();
							try {
								value.put("affs", aff);
								update.put("$pop", value);
								JSONObject user = getCurrentUser();
								client.update(user.getJSONObject("_id").getString("$oid"), update);
							} catch (JSONException e1) {

								e1.printStackTrace();
							}
							
							dialog.dismiss();
						}
					});
					builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					dialog = builder.create();
					dialog.show();
				}
			});
			
			return v;
		}
		
    	
    }
    
    private JSONObject getCurrentUser(){
    	List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(new BasicNameValuePair("q","{\"username\":\"" + db.getAccount() + "\"}"));
		
		JSONObject user = client.findOne(qparams);
		return user;
    }
	

	
}
